<template>
  <div class="code" v-show="showCode">
    <div class="code-top">
      <el-select class="encode-select" placeholder="请选择编码" v-model="encode" @change="changeEncode">
        <el-option value="utf8" label="utf8编码"></el-option>
        <el-option value="gbk" label="gbk编码"></el-option>
      </el-select>
      <el-button style="margin: 0 10px" type="primary" @click="copy">复制</el-button>
    </div>
    <highlightjs autodetect :code="textContent" />
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";
import useClipboard from "vue-clipboard3";
import { ElMessage } from "element-plus";
const { toClipboard } = useClipboard();

const showCode = ref(false);
const textContent = ref("");
const blobResult = ref();
const encode = ref("utf8");

// 选择编码
const changeEncode = (e) => {
  encode.value = e;
  readBlob();
};

const readBlob = () => {
  const reader = new FileReader();
  reader.readAsText(blobResult.value, encode.value);
  reader.onerror = () => {
    ElMessage.error("读取文件失败");
  };
  reader.onload = () => {
    textContent.value = reader.result;
  };
};
const copy = async () => {
  await toClipboard(textContent.value);
  ElMessage.success("复制成功");
};

const open = async (url) => {
  console.log("读取文件", url);
  let response;
  try {
    response = await axios.get(url);
  } catch (error) {
    console.error("读取文件失败:", error);
    ElMessage.error(error?.response?.data?.error || "读取文件失败");
    return;
  }
  console.log("读取文件成功");
  console.log(response);
  const blob = new Blob([response.data], {
    type: response.headers["content-type"],
  });
  blobResult.value = blob;
  readBlob();
  showCode.value = true;
};

const close = () => {
  textContent.value = "";
  showCode.value = false;
  blobResult.value = null;
};

defineExpose({
  open,
  close,
});
</script>
<style scoped>
.code-top {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.encode-select {
  width: 150px;
}
</style>
